package com.nettest.action.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.nettest.action.BaseJsonAction;
import com.nettest.entity.system.Menu;
import com.nettest.pojo.TreeVo;
import com.nettest.service.system.MenuService;
import com.nettest.util.StringUtils;
@Action("menuManage")
@Namespace("/system/menu")
@Results({@Result(name = "success", location = "/system/menuManage.jsp") })
public class MenuManageAction extends BaseJsonAction {
	
	private static final long serialVersionUID = -8688383723959272001L;
	static Logger logger = Logger.getLogger(MenuManageAction.class
			.getName());
	
	private List<TreeVo> trees;
	private Menu menu;
	private String id;
	private String operate;
	private String menuId;
	@Autowired
	private MenuService menuService;

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	
	@Action(value = "list", results = { @Result(name = "success", type = "json", params = {
			"ignoreHierarchy", "false", "excludeNullProperties", "true",
			"excludeProperties", "menu,menuService","root","trees" }) })
	public String list() throws Exception  {
		try {
			if(id == null) {
				List<Menu> topMenu = menuService.getTopMenu(null);
				transferVo(topMenu);
				TreeVo root = new TreeVo();
				root.setText("菜单");
				root.setId("0");
				root.setState("open");
				root.setChildren(new ArrayList<TreeVo>(trees));
				trees = new ArrayList<TreeVo>();
				trees.add(root);
			} else {
				List<Menu> subMenu = menuService.getSubMenu(id);
				transferVo(subMenu);
			}
		} catch (Exception e) {
			this.addActionMessage(e.getMessage());
		}
		return SUCCESS;
	}
	
	protected void transferVo(List<Menu> menus) {
		trees = new ArrayList<TreeVo>();
		TreeVo treeVo = null;
		for (Menu menu : menus) {
			treeVo = new TreeVo();
			treeVo.setId(menu.getMenuId());
			treeVo.setText(menu.getMenuName());
			treeVo.setAttributes(menu.getMenuAction());
			trees.add(treeVo);
		}
	}
	
	@Action(value = "menuEdit",results={@Result(name = "success", location = "/system/menuEdit.jsp")})
	public String getOneRole() throws Exception {
		operate = StringUtils.isBlank(operate) ? "editView" : operate;
		if (!StringUtils.isBlank(menuId)) {
			menu = menuService.getMenuById(menuId);
		}
		
		if ("insertSub".equalsIgnoreCase(operate)) {
			String parentRoleId = menu.getMenuId();
			menu.setMenuId(null);
			menu.setParentId(parentRoleId);
			menu.setMenuName(null);
			menu.setMenuAction(null);
			menu.setMenuFullPath(null);
		}
		return SUCCESS;
	}
	
	/**
	 * 添加菜单项
	 */
	@Action(value = "menuSave",results={@Result(name = "success", location = "/system/menuEdit.jsp")})
	public String menuSave() throws Exception {
		if ("insertSub".equalsIgnoreCase(operate)) {
			menu.setMenuId(this.generateNodeId(menu.getParentId()));
			menu.setIsLeaf(true);
			menuService.save(menu);
		}
		else {
			Menu menuById = menuService.getMenuById(menu.getMenuId());
			if(menuById != null) {
				menuById.setMenuId(menu.getMenuId());
				menuById.setParentId(menu.getParentId());
				menuById.setMenuName(menu.getMenuName());
				menuById.setIsShortcut(menu.getIsShortcut());
				menuById.setMenuAction(menu.getMenuAction());
				menuById.setMenuFullPath(menu.getMenuFullPath());
				menuService.save(menuById);
			}
		}
		
		return SUCCESS;
	}
	/**
	 * 删除菜单项
	 * @param parentId
	 * @return
	 * @throws Exception
	 */
	@Action(value = "delete",results={@Result(name = "success", location = "/system/menuEdit.jsp")})
	public String delete() throws Exception {
		if (!StringUtils.isBlank(menuId)) {
			deleteMenu(menuId);
		}
		
		return SUCCESS;
	}

	private void deleteMenu(String parentId) throws Exception {
		List<Menu> allMenus = menuService.selectChildByParentId(parentId);
		for (Menu menu : allMenus) {
			deleteMenu(menu.getMenuId());
		}
		
		menuService.deleteMenuById(parentId);//删除菜单项
		
	}
	
	public List<TreeVo> getTrees() {
		return trees;
	}

	public void setTrees(List<TreeVo> trees) {
		this.trees = trees;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	/**
	 * 生成节点id
	 * @param nodeId
	 * @return
	 */
	protected String generateNodeId(String nodeId){
    	//001001,001001001,001001002,002002...
    	String newNodeId=null;
    	List<Menu> list=menuService.getAllMenu();
    	int i=0;
    	for (Menu menu : list) {
    		if(menu.getParentId() != null &&
    				menu.getParentId().equals(nodeId)){
        		i++;
        	}
		}
    	
    	if(i==0){
    		newNodeId=nodeId+"001";
    	}else{
    		String maxNodeId=menuService.selectMaxMenuId(nodeId);
    		int number=Integer.parseInt(maxNodeId.substring(nodeId.length()))+1;
    		String value=String.valueOf(number).length()==3?String.valueOf(number):String.valueOf(number).length()==2?"0"+String.valueOf(number):String.valueOf(number).length()==1?"00"+String.valueOf(number):"001";
    		if("0".equals(nodeId)){
    			newNodeId=value;
    		}else{
    			newNodeId=maxNodeId.substring(0,nodeId.length())+value;
    		}
    	}
    	return newNodeId;
    }

	public String getOperate() {
		return operate;
	}

	public void setOperate(String operate) {
		this.operate = operate;
	}

	public String getMenuId() {
		return menuId;
	}

	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}
}
